JavaScript syntax
part 46/59 · 107.4 KB total
──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
The number of arguments given when calling a function may not necessarily correspond to the number of arguments in the function definition; a named argument in the definition that does not have a matching argument in the call will have the value undefined (that can be implicitly cast to false). Within the function, the arguments may also be accessed through the arguments object; this provides access to all arguments using indices (e.g. arguments[0], arguments[1], ... arguments[n]), including those beyond the number of named arguments. (While the arguments list has a .length property, it is not an instance of Array; it does not have methods such as .slice(), .sort(), etc.)
function add7(x, y) {
if (!y) {
y = 7;
}
console.log(x + y + arguments.length);
};
add7(3); // 11
add7(3, 4); // 9
Primitive values (number, boolean, string) are passed by value. For objects, it is the reference to the object that is passed.
const obj1 = {a : 1};
const obj2 = {b : 2};
function foo(p) {
p = obj2; // Ignores actual parameter
p.b = arguments[1];
}
foo(obj1, 3); // Does not affect obj1 at all. 3 is additional parameter
console.log(`${obj1.a} ${obj2.b}`); // writes 1 3
Functions can be declared inside other functions, and access the outer function's local variables. Furthermore, they implement full closures by remembering the outer function's local variables even after the outer function has exited.
let t = "Top";
let bar, baz;
function foo() {
let f = "foo var";
bar = function() { console.log(f) };
baz = function(x) { f = x; };
}
──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────